<template>
  <div class="login-container">
    <div class="login-box">
      <h2>登录</h2>
      <p class="login-tip">请使用与后端数据匹配的用户名和密码</p>
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <input
            type="text"
            v-model="name"
            placeholder="用户名"
            required
            class="form-input"
          />
        </div>
        <div class="form-group">
          <input
            type="password"
            v-model="password"
            placeholder="密码"
            required
            class="form-input"
          />
        </div>
        <button type="submit" class="login-button" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
        <button type="button" class="register-button" @click="goToRegister">
          注册账号
        </button>
        <p v-if="error" class="error-message">{{ error }}</p>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const name = ref('')
const password = ref('')
const error = ref('')
const isLoading = ref(false)

const goToRegister = () => {
  router.push('/reg')
}

const handleLogin = async () => {
  try {
    error.value = ''
    isLoading.value = true
    console.log('开始登录流程，尝试获取用户列表...')

    // 首先获取用户列表
    const response = await fetch('http://localhost:3005/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    const data = await response.json()
    
    // 记录API返回信息
    console.log('成功获取API数据')
    
    // 为安全起见，只在控制台输出用户数量而不是完整数据
    try {
      if (data.result && Array.isArray(data.result)) {
        console.log(`获取到 ${data.result.length} 个用户记录`)
      }
    } catch (err) {
      // 忽略日志错误
    }

    if (!response.ok || !data.result || !Array.isArray(data.result)) {
      console.error('API响应格式错误:', {
        status: response.status,
        ok: response.ok,
        hasResult: !!data.result,
        isArray: Array.isArray(data.result || null)
      })
      error.value = '服务器响应错误，请稍后重试'
      return
    }

    console.log(`获取到 ${data.result.length} 个用户记录，正在验证凭据...`)

    // 定义用户对象的类型
    interface User {
      name: string;
      password: string;
      [key: string]: any; // 允许其他可能的属性
    }

    // 在前端进行用户名和密码匹配
    const user = data.result.find(
      (u: User) => u.name === name.value && u.password === password.value
    )

    if (user) {
      // 登录成功
      console.log('凭据验证成功，用户:', name.value)
      sessionStorage.setItem('isLoggedIn', 'true')
      sessionStorage.setItem('username', name.value)
      
      // 短暂延迟以显示成功效果
      setTimeout(() => {
        console.log('跳转到首页...')
        router.push('/')
      }, 500)
    } else {
      // 登录失败
      console.log('凭据验证失败: 用户名或密码不匹配')
      error.value = '用户名或密码错误'
    }
  } catch (e) {
    console.error('登录请求异常:', e)
    error.value = '登录失败，请检查网络连接或服务器状态'
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
  background: linear-gradient(135deg, #42b883 0%, #35495e 100%);
  animation: gradientAnimation 10s ease infinite;
  background-size: 200% 200%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

@keyframes gradientAnimation {
  0% { background-position: 0% 50% }
  50% { background-position: 100% 50% }
  100% { background-position: 0% 50% }
}

.login-box {
  width: 90%;
  max-width: 380px;
  padding: 35px 25px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transform: translateY(0);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

h2 {
  text-align: center;
  color: #35495e;
  margin-bottom: 35px;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.form-group {
  position: relative;
}

.form-input {
  width: 100%;
  padding: 15px;
  border: 2px solid #e8e8e8;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease; 
  background: #ffffff;
  box-sizing: border-box;
  color: #333;
}

.form-input:focus {
  border-color: #42b883;
  outline: none;
  box-shadow: 0 0 0 3px rgba(66, 184, 131, 0.2);
}

.login-button {
  background: linear-gradient(45deg, #42b883, #3aa876);
  color: white;
  padding: 15px;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.login-button:hover {
  background: linear-gradient(45deg, #3aa876, #42b883);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(66, 184, 131, 0.3);
}

.login-button:disabled {
  background: linear-gradient(45deg, #9be0c0, #b8e9d3);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.register-button {
  background: transparent;
  color: #42b883;
  padding: 15px;
  border: 2px solid #42b883;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.register-button:hover {
  background: rgba(66, 184, 131, 0.1);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(66, 184, 131, 0.1);
}

.error-message {
  color: #ff6b6b;
  text-align: center;
  margin: 0;
  font-size: 14px;
  padding: 8px;
  border-radius: 8px;
  background: rgba(255, 107, 107, 0.1);
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

.login-tip {
  text-align: center;
  color: #666;
  margin: -20px 0 25px;
  font-size: 14px;
  line-height: 1.5;
}
</style>